@tool
class_name ContextBehavior_Seek
extends BaseContextBehavior

#region 属性
@export var force:float
## 是否添加arrive特点，即靠近会减速
@export var is_arrive:bool = false
@export var target_reached_threshold:float = 0.5
## 实际的到达半径是否需要加上代理半径
@export var is_target_reached_threshold_add_body_radius:bool = true
@export var slow_radius:float = 2
## 实际的减速半径是否需要加上代理半径
@export var is_slow_radius_add_body_radius:bool = true
## 是否到达最后发现目标的地方
@export var is_arrive_final_target_point:bool
## 是否在切换enable时清空跟踪信息
@export var is_clear_target_point_by_switch_enable:bool
var target_point
var is_arrived:bool = false
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
func init():
	super()
func setter_enable(value):
	super(value)
	if is_clear_target_point_by_switch_enable:
		target_point = null
		is_arrived = false
func calc_steering(behaviors_owner:Node,agent:SteeringBehaviorAgent,delta:float):
	super(behaviors_owner,agent,delta)
	var detect_component:DetectComponent = agent.entity.get_component(DetectComponent)
	if not detect_component:
		return
	var detector_target:Detector_Target = detect_component.get_detector(GameEnum.DetectorType.Target)
	if not detector_target and (target_point == null or is_arrived):
		return
	var targets = detector_target.get_targets(agent.get_pos(),0,Callable(),1)
	if targets.size() >= 1:
		target_point = get_target_pos(targets[0])
		is_arrived = false
	elif target_point == null or (targets.size() < 1 and not is_arrive_final_target_point):
		target_point = null
		return
	var to_target = target_point - agent.get_pos()
	var distance = to_target.length()
	if distance < (target_reached_threshold if not is_target_reached_threshold_add_body_radius else target_reached_threshold + agent.body_radius):
		is_arrived = true
		return
	var interest = to_target.normalized() * sensitive
	var real_slow_radius = slow_radius if not is_slow_radius_add_body_radius else slow_radius + agent.body_radius
	if distance <= real_slow_radius:
		interest *= distance / real_slow_radius
	agent.add_linear_force_interest(interest * force)
#endregion
#region 公共方法
func get_target_pos(target:Node2D) -> Vector2:
	return target.global_position
#endregion
#region 私有方法
#endregion
#region 生命周期函数
func _init() -> void:
	if Engine.is_editor_hint():
		resource_local_to_scene = true
	behavior_type = GameEnum.ContextBehaviorType.Seek
func draw() -> void:
	super.draw()
	if target_point != null and not is_arrived:
		GameSteeringBehaviorDebug.draw_circle(target_point,2,Color.RED)
#endregion
